package com.h.forum.services.impl;

import com.h.forum.common.constant.Constants;
import com.h.forum.common.enums.ResultCode;
import com.h.forum.common.utils.JWTUtil;
import com.h.forum.common.utils.StringUtil;
import com.h.forum.dao.ArticleMapper;
import com.h.forum.exception.ApplicationException;
import com.h.forum.pojo.model.Article;
import com.h.forum.pojo.model.Board;
import com.h.forum.pojo.request.ArticleCreateRequest;
import com.h.forum.pojo.response.AppResult;
import com.h.forum.pojo.response.UserInfoResponse;
import com.h.forum.services.IArticleService;
import com.h.forum.services.IBoardService;
import com.h.forum.services.IUserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    @Resource
    private ArticleMapper articleMapper;

    // 添加和用户、板块的联合操作，这里需要注意循环引用的问题，这里在帖子表里面引入了用户和板块，那么在用户和板块里面就不能再引入帖子操作
    @Resource
    private IUserService userService;

    @Resource
    private IBoardService boardService;

    /**
     * 创建新的帖子
     * @param article
     */
    @Override
    public void create(Article article) {

        // 1、非空校验
        if (article == null
                || article.getBoardId() == null
                || article.getTitle() == null
                || article.getUserId() == null
                || article.getContent() == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 2、创建写入数据库的Article对象，并进行初始化
        article.setVisitCount(0); // 访问数
        article.setReplyCount(0); // 回复数
        article.setLikeCount(0); // 点赞数
        article.setDeleteState((byte) 0); // 是否删除
        article.setState((byte) 0); // 设置状态
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);

        // 3、写入数据库中
        int articleRow = articleMapper.insertSelective(article);
        // 4、检验结果
        if (articleRow != 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_CREATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_CREATE));
        }

        // 5、获取用户信息，根据用户Id
        UserInfoResponse user = userService.selectById(article.getUserId());
        // 6、校验结果
        if (user == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_CREATE.toString() + ", 发贴失败, user id = " + article.getUserId());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_CREATE));
        }
        // 7、在都没有问题的前提下，进行更新用户表中的帖子数
        userService.addOneArticleCountById(user.getId());

        // 8、获取板块的信息，根据板块Id
        Board board = boardService.selectById(article.getBoardId());
        // 9、校验结果
        if (board == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_CREATE.toString() + ", 发贴失败, board id = " + article.getBoardId());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_CREATE));
        }
        
        // 10、更新板块中的帖子数量
        boardService.addOneArticleCountById(board.getId());

        // 11、更新成功
        // 打印日志
        log.info(ResultCode.SUCCESS.toString() + ", user id = " + article.getUserId()
                + ", board id = " + article.getBoardId() + ", article id = "+article.getId() + "发帖成功");
    }

    /**
     * 查询所有的列表信息，这个是前端首页的界面显示
     * @return
     */
    @Override
    public List<Article> selectAll() {
        // 直接查询结果
        List<Article> articles = articleMapper.selectAll();

        return articles;
    }

    /**
     * 根据 板块Id进行查询对应的板块信息
     * @param boardId
     * @return
     */
    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        // 校验
        if (boardId == null || boardId <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 查询板块信息
        Board board = boardService.selectById(boardId);
        if (board == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString() + ", board id = " + boardId);
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }

        // 存在板块信息，进行查询
        List<Article> articles = articleMapper.selectAllByBoardId(boardId);

        return articles;
    }

    /**
     * 根据帖子Id查询帖子详情
     * @param id
     * @return
     */
    @Override
    public Article selectDetailById(Long id) {
        // 校验
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询帖子的详细信息
        Article article = articleMapper.selectDetailById(id);
        if (article == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        // 更新访问次数，每个人查询详细的信息，访问次数就+1
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount() + 1);

        // 保存到数据库中
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }

        // 更新返回对象的访问次数
        article.setVisitCount(article.getVisitCount() + 1);

        return article;
    }

    /**
     * 编辑帖子
     * @param article
     */
    @Override
    public void modify(Article article) {
        // 非空校验
        if (article == null
                || article.getId() == null
                || StringUtil.isEmpty(article.getTitle())
                || StringUtil.isEmpty(article.getContent())) {
            // 校验不通过
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 构建需要更新的帖子
        Article updateArticle = new Article();
        updateArticle.setId(article.getId()); // id
        updateArticle.setTitle(article.getTitle()); // 标题
        updateArticle.setContent(article.getContent()); // 内容
        updateArticle.setUpdateTime(new Date()); // 更新时间

        // 调用Mapper
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
        // 更新成功
    }

    /**
     * 根据帖子Id，进行查询对应的信息
     * @param id
     * @return
     */
    @Override
    public Article selectById(Long id) {
        // 非空校验
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 调用DAO层
        Article article = articleMapper.selectByPrimaryKey(id);
        return article;
    }

    /**
     * 点赞功能
     * @param id
     */
    @Override
    public void thumbsUpById(Long id) {
        // 校验
        if(id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 校验这个Id的帖子是否正常
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null
                || article.getDeleteState().equals(Constants.IS_DELETE_STATE)) {
            // 帖子不存在
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        // 在帖子存在的情况下，校验这个帖子的状态是否是不符的
        if (article.getState().equals(Constants.IS_STATUS_STATE)) {
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_BANNED));
        }

        // 都没有问题下，进行构造更改对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount() + 1);
        updateArticle.setUpdateTime(new Date());

        // 调用DAO层
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
        // 点赞成功。
    }

    /**
     * 删除帖子的功能
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        // 校验参数
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 根据Id查询帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null
                || article.getDeleteState().equals(Constants.IS_DELETE_STATE)) {
            // 打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString() + ", article id = " + id);
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }

        // 构造修改对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte) 1);
        updateArticle.setUpdateTime(new Date());

        // 进行交互DAO层，进行删除操作
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }

        // 帖子删除成功，那么进行减少 用户和板块 的帖子数
        userService.subOneArticleCountById(article.getUserId());
        boardService.subOneArticleCountById(article.getBoardId());

        // 删除成功
        log.info("删除帖子成功, article id = " + article.getId() + ", user id = " + article.getUserId() + ".");
    }

    /**
     * 对于回复数量进行 加一 操作
     * @param id
     */
    @Override
    public void addOneReplyCountById(Long id) {
        // 非空校验
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 获取帖子记录
        Article article = articleMapper.selectByPrimaryKey(id);
        // 校验帖子状态
        if (article == null || article.getDeleteState().equals(Constants.IS_DELETE_STATE)) {
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        // 帖子已封帖
        if (article.getState().equals(Constants.IS_STATUS_STATE)) {
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_BANNED));
        }

        // 创建修改的对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setReplyCount(article.getReplyCount() + 1);
        updateArticle.setUpdateTime(new Date());

        // 调用DAO层
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
    }

    /**
     * 根据用户Id、，获取到对应的帖子列表
     * @param userId
     * @return
     */
    @Override
    public List<Article> selectByUserId(Long userId) {
        // 检查
        if (userId == null
                ||userId <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 根据ID，检查用户是否存在
        UserInfoResponse userInfo = userService.selectById(userId);
        if (userInfo == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + ", user id = " + userId);
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        // 调用DAO层
        List<Article> articles = articleMapper.selectByUserId(userId);

        return articles;
    }
}
